#!/usr/bin/python2.7
# ! -*- coding:utf-8 -*-

import commands
import json
import os
import sys

BASE_DIR = os.path.dirname(os.path.abspath('/usr/local/lib/python2.7/site-packages/requests'))  # 存放c.py所在的绝对路径

sys.path.append(BASE_DIR)
import requests
from django.core.management.base import BaseCommand

import datetime

reload(sys)
sys.setdefaultencoding('UTF-8')

# _LOGGER = logging.getLogger(__name__)

# jp_monitor group
# _TG_DEPLOY_REMIND = -301835231
# my test group
# _TG_DEPLOY_REMIND = -261523497
# 财务告警group
# _TG_DEPLOY_REMIND = -261523497
_TG_DEPLOY_REMIND = -360174479

_SEND_TEXT_TELE = 'https://api.telegram.org/bot773604083:AAFuxwAqmlUN6QSfJ9zHhb6BKo-w5ozTEHc/sendMessage'

GROUP_ID = 4335


def _get_mechine_ip(machine_name):
    if machine_name == 'console':
        return '103.230.240.174' + ' ' + u'justpay正式控制台'
    elif machine_name == 'release':
        return '219.135.56.195' + ' ' + u'justpay测试控制台'
    elif machine_name == 'online':
        return '103.230.242.40' + ' ' + u'witch生产环境'
    elif machine_name == 'online_game':
        return '103.71.50.181' + ' ' + u'dwc生产环境'
    elif machine_name == 'online_dbl':
        return '103.230.243.10' + ' ' + u'dbl生产环境'
    elif machine_name == 'online_zs':
        return '103.230.243.99' + ' ' + u'zs生产环境'
    else:
        return 'no one'


def _form_msg():
    with open('/Users/channing/.zsh_history', 'r') as f:
        line = f.readlines()
    for i in line[::-1]:
        if 'deploy.sh' in i:
            machine_name = i.split(" ")[-1].strip('\n')
            break;
    git_log_newest_content = commands.getoutput("git log|sed -n '5p'")
    try:
        content = git_log_newest_content.split('|')[1].encode('utf8')
    except:
        content = git_log_newest_content.split('|')[0].encode('utf8')
    auther = commands.getoutput("git log|sed -n '2p'")
    msg = {
        u'上线产品: ': 'justpay' + '\n',
        u'机器: ': machine_name + ' ' + _get_mechine_ip(machine_name) + '\n',
        u'预计上线时间: ': datetime.datetime.now().strftime('%Y.%m.%d-%H:%M:%S') + '\n',
        u'更新内容: ': unicode(content) + '\n',
        u'服务/模块: ': unicode(git_log_newest_content.split('|')[0].encode('utf8')) + '\n',
        u'作者: ': auther + '\n',
        u'TIPS: ': u'####请在git commit时，将内容变成"(服务/模块)|(更新内容)"格式，以|区分 ###################################' + '\n'
    }
    return _send_tg(msg)


def _send_tg(msg_all):
    msg_trans = []
    for k, v in msg_all.iteritems():
        msg_trans.append(k + v)

    msg_finial = ''
    for i in msg_trans:
        msg_finial += i + '\n'

    if sys.getsizeof(msg_finial) > 4000:
        # 分段分数
        times = int(sys.getsizeof(msg_finial) / 4000 + 1)
        # 每段的长度
        int(len(msg_finial) / times)
        i = 0
        while i < times:
            send_channel_text_msg_tele(_TG_DEPLOY_REMIND, msg_finial[
                                                          i * int(len(msg_finial) / times):int(
                                                              len(msg_finial) / times) + i * int(
                                                              len(msg_finial) / times)])
            print "msg is: %s", msg_finial[
                                i * int(len(msg_finial) / times):int(len(msg_finial) / times) + i * int(
                                    len(msg_finial) / times)]
            i += 1
    else:
        send_channel_text_msg_tele(_TG_DEPLOY_REMIND, msg_finial)


def send_channel_text_msg_tele(chat_id, chat_text):
    chat_text = chat_text.replace('[', '-').replace(']', '-').replace('_', '-')
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    post_data = {
        "chat_id": chat_id,
        "text": chat_text,
        "parse_mode": "Markdown",
    }
    j = json.dumps(post_data, separators=(',', ':'))
    print j
    response = requests.post(_SEND_TEXT_TELE, data=j, headers=headers,
                             timeout=5)
    print response.text


class Command(BaseCommand):
    def handle(self, **options):
        try:
            _form_msg()
        except Exception as e:
            print "reminder error %s" % e


if __name__ == "__main__":
    Command().handle()
